import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import Upload from 'rc-upload';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Radio,
  Badge,
  Divider,
  Cascader,
} from 'antd';
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const confirm = Modal.confirm;
import DescriptionList from 'components/DescriptionList';
const { Description } = DescriptionList;
const RadioGroup = Radio.Group;

import { tagCategoryListAll, tagSave, tagDelete } from '../../services/api';
import { getArrFromObj, getToken, getCurrent } from '../../utils/utils';
import config from '../../common/config';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './tagList.less';

import uploadPng from '../../assets/upload.png';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const PAGE_STATUS_MAP = {
  '0': '无效',
  '1': '有效',
};

const PAGE_STATUS_ARR = getArrFromObj(PAGE_STATUS_MAP);

const GENERATE_MODE_MAP = {
  1: '系统生成',
  2: '用户生成',
  3: '手工生成',
};

const GENERATE_MODE_ARR = getArrFromObj(GENERATE_MODE_MAP);

const PAGE_SIZE = 10;

@connect(({ tagList, loading }) => {
  return {
    tagList,
    loading: loading.models.tagList,
  };
})
@Form.create()
export default class List extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    pageNumSTC: 1,
    pageSizeSTC: 10,
    id: null,

    title: null,
    status: '1',
    category: '1',

    pcTitle: null,
    pcKeywords: null,
    pcDesc: null,
    mobileTitle: null,
    mobileKeywords: null,
    mobileDesc: null,
    content: '',

    imgOptions: {},
    coverUrl: null,
    tagCategoryList: [],
    category0List: [],
    category1List: [],
    category2List: [],
    category3List: [],
  };

  componentDidMount() {
    this.getImgOptions();
    this.init();
  }

  getImgOptions() {
    const token = getToken();

    const imgOptions = {
      action: config.serveraddress + '/upload/putObject?dataType=0',
      data: { dataType: 0 },
      headers: {
        Authorization: 'Bearer ' + token,
      },
      multiple: false,
      beforeUpload(file) {
        console.log('beforeUpload', file.name);
      },
      onStart: file => {
        console.log('onStart', file.name);
      },
      onProgress(step, file) {},
    };

    this.setState({
      imgOptions,
    });
  }

  async init() {
    const { dispatch } = this.props;
    dispatch({
      type: 'tagList/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });

    const response = await tagCategoryListAll({ itemId: 0 });
    if (response.data) {
      const tagCategoryList = this.buildTreeData(response.data.children);
      this.setState({
        tagCategoryList,
      });
    }
  }

  buildTreeData(data) {
    for (let i = 0; i < data.length; i++) {
      if (data[i].children) {
        data[i].label = data[i].name;
        data[i].value = data[i].id;
        this.buildTreeData(data[i].children);
      }
    }
    return data;
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});
    this.state.pageNumSTC = pagination.current;
    this.state.pageSizeSTC = pagination.pageSize;
    const params = {
      ...formValues,
      ...filters,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'tagList/queryList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'tagList/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (!fieldsValue.name) {
        delete fieldsValue.name;
      }
      if (!fieldsValue.hierarchyId) {
        delete fieldsValue.hierarchyId;
      }
      if (!fieldsValue.generateMode) {
        delete fieldsValue.generateMode;
      }

      this.state.pageNumSTC = 1;
      const values = {
        ...fieldsValue,
        pageNum: 1,
        pageSize: PAGE_SIZE,
      };

      dispatch({
        type: 'tagList/queryList',
        payload: values,
      });
    });
  };

  handleShowModal = e => {
    e.preventDefault();
    this.setState({
      id: null,
      modalVisible: true,
      levelRule: '',
      name: '',
    });
  };

  handleCancel = e => {
    this.setState({
      modalVisible: false,
    });
  };

  async handleSave(e) {
    const { name, tagSet } = this.state;
    if (!name) {
      return message.error('请填写标签名称');
    }

    if (!tagSet || !tagSet.length) {
      return message.error('请选择标签体系');
    }

    await this.doSave();
  }

  async doSave() {
    const { dispatch } = this.props;

    const { id, name, tagSet } = this.state;

    let response = {};
    if (id) {
      const params = { id, name, generateMode: 3 };
      if (tagSet[0]) {
        params.hierarchyId = tagSet[0];
      }
      if (tagSet[1]) {
        params.category1Id = tagSet[1];
      }
      if (tagSet[2]) {
        params.category2Id = tagSet[2];
      }
      if (tagSet[3]) {
        params.category3Id = tagSet[3];
      }
      response = await tagSave(params);
    } else {
      const params = { name, generateMode: 3 };
      if (tagSet[0]) {
        params.hierarchyId = tagSet[0];
      }
      if (tagSet[1]) {
        params.category1Id = tagSet[1];
      }
      if (tagSet[2]) {
        params.category2Id = tagSet[2];
      }
      if (tagSet[3]) {
        params.category3Id = tagSet[3];
      }
      response = await tagSave(params);
    }

    if (response.code === 200) {
      this.setState({
        modalVisible: false,
      });

      const { dispatch, form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        if (!fieldsValue.name) {
          delete fieldsValue.name;
        }
        if (!fieldsValue.hierarchyId) {
          delete fieldsValue.hierarchyId;
        }
        if (!fieldsValue.generateMode) {
          delete fieldsValue.generateMode;
        }
        const values = {
          ...fieldsValue,
          pageNum: this.state.pageNumSTC || 1,
          pageSize: this.state.pageSizeSTC || 10,
        };
        dispatch({
          type: 'tagList/queryList',
          payload: values,
        });
      });

      // await this.init();
    } else {
      message.error(response.message);
    }
  }

  handleReply(item) {
    this.setState({
      ...item,
      modalVisible: true,
    });
  }

  handleOnchange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  onChange(field, value, dateString) {
    this.setState({
      [field]: dateString,
    });
  }

  handleSelectOnchange(field, value) {
    if (field === 'hierarchyId') {
    }
    this.setState({
      [field]: value,
    });
  }

  onRadioChange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  handleEdit(item) {
    this.setState({
      ...item,
      content: BraftEditor.createEditorState(item.content),
      modalVisible: true,
    });
  }

  handleDelete(item) {
    debugger;
    confirm({
      title: '确认删除',
      content: '是否删除？',
      onOk: (async () => {
        let { errno, errmsg, data } = await tagDelete({
          id: item.id,
        });
        if (!errno) {
          message.success('删除成功');
          this.init();
        }
      }).bind(this),
      onCancel() {},
    });
  }

  handleShowAddNewTag() {
    this.setState({
      modalVisible: !this.state.modalVisible,

    });
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="">
              {getFieldDecorator('name')(<Input placeholder="标签名称" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="">
              {getFieldDecorator('hierarchyId')(
                <Select style={{ width: '100%' }} placeholder="标签体系">
                  <Option value="">全部</Option>
                  {this.state.tagCategoryList.map(item => {
                    return (
                      <Option key={item.id} value={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
              )}
            </FormItem>
            {/*<FormItem label="">*/}
            {/*  {getFieldDecorator('hierarchyId')(<Input placeholder="标签体系" />)}*/}
            {/*</FormItem>*/}
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="">
              {getFieldDecorator('generateMode')(
                <Select style={{ width: '100%' }} placeholder="标签生成方式">
                  <Option value="">全部</Option>
                  {GENERATE_MODE_ARR.map(item => {
                    return (
                      <Option key={item.id} value={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={6} sm={24}>
            <span style={{ float: 'left', marginBottom: 24 }}>
              <Button type="primary" onClick={this.handleSearch.bind(this)}>
                查询
              </Button>
              &nbsp;&nbsp;
              <Button type="primary" onClick={this.handleShowAddNewTag.bind(this)}>
                新增标签
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  handleEditorChange = editorState => {
    this.setState({
      content: editorState,
    });
  };

  uploadSuccess(res, field) {
    this.setState({
      [field]: res.data,
    });
  }

  uploadError(res, field) {
    debugger;
  }

  onCascaderChange(values) {
    this.setState({
      tagSet: values,
    });
  }

  render() {
    let { tagList: { data }, loading } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { selectedRows, modalVisible, imgOptions, coverUrl } = this.state;

    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        render: (val, item, index) => (
          <span>{(data.pagination.current - 1) * data.pagination.pageSize + index + 1}</span>
        ),
      },
      {
        title: '标签名称',
        ellipsis: true,
        width: 100,
        dataIndex: 'name',
      },
      {
        title: '标签生成方式',
        dataIndex: 'generateModeName',
      },
      {
        title: '标签分类',
        dataIndex: 'category1Name',
        render: (val, item) => (
          <span>{[item.category1Name, item.category2Name, item.category3Name].join('-')}</span>
        ),
      },
      {
        title: '标签所属体系',
        dataIndex: 'hierarchyName',
      },
      {
        title: '操作',
        dataIndex: '',
        render: (val, item) => (
          <span>
            <a href="javascript:;" onClick={this.handleEdit.bind(this, item)}>
              编辑
            </a>&nbsp;<a href="javascript:;" onClick={this.handleDelete.bind(this, item)}>
              删除
            </a>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="标签管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTable
              disableSelect={true}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        <Modal
          maskClosable={false}
          width="70%"
          title={!this.state.id ? '新增标签' : '编辑标签'}
          visible={this.state.modalVisible}
          onOk={this.handleSave.bind(this)}
          onCancel={this.handleCancel.bind(this)}
        >
          <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
            <Col span={24}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="标签名称">
                  <Input
                    style={{ width: '300px' }}
                    value={this.state.name}
                    onChange={this.handleOnchange.bind(this, 'name')}
                  />
                </Description>
              </DescriptionList>
            </Col>
          </Row>
          <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
            <Col span={24}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="标签体系">
                  <Cascader
                    options={this.state.tagCategoryList}
                    placeholder="Please select"
                    onChange={this.onCascaderChange.bind(this)}
                  />
                </Description>
              </DescriptionList>
            </Col>
          </Row>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
